// Anode.h
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "Anode-wget.h"
#define regsgH(mt) \
  signal(SIGABRT,mt); \
  signal(SIGFPE,mt); \
  signal(SIGILL,mt); \
  signal(SIGINT,mt); \
  signal(SIGSEGV,mt); \
  signal(SIGTERM,mt)  
#define nil (NULL)
typedef struct {
	char*type;
	char*mark;
	char*script;
} elemt;
typedef struct {
	raweb rdat;
	elemt lsfe;
} website;
unsigned tkbg,tknd;
void next(const char*rcode) {
    tkbg=tknd+1;
	Bool fspc=True;
    unsigned i;
	for(i = tkbg; i < strlen(rcode); i++) {
		if(rcode[i]=='>'&&rcode[i-1]!='@') {
			tknd=i;
			break;
		} else if((rcode[i]==' '||rcode[i]=='\n'||rcode[i]=='\t')&&fspc) {
			++tkbg;
		} else {
			fspc=False;
		}
	}
	if(tkbg==1) tkbg--;
    return ;
}
char*substr(const char*str,int beg,int end) {
	char*sub=(char*)malloc((end-beg+1)*sizeof(char));
	for(unsigned i = 0; i<(end-beg+1); i++) {
		sub[i]=str[i+beg];
	}
	return sub;
}
elemt* parse(const char*rcode) {
    char*alab=(char*)malloc(20*sizeof(char*)),*script=(char*)malloc(1024*sizeof(char*)),*txlb=(char*)malloc(64*sizeof(char*));
    elemt* list=(elemt*)malloc(1*sizeof(elemt));
    unsigned i,mark,lslen=0;
    do {
        next(rcode);
        sscanf(substr(rcode,tkbg,tknd),"%[^:]",alab); // simp-regexp
		for(i = tkbg+strlen(alab); ; i++) {
			if(rcode[i]=='<') {
			    strcpy(script,substr(rcode,i+1,tknd-1));
			    for(i=0; i<strlen(script)-1; i++) {
			        if(script[i]=='@'&&script[i+1]=='>') {
			            script[i]=21;
			        }
			    }
			    for(i=0,mark=-1; i<strlen(script)-1; i++) {
			    	if(script[i]=='[') mark=i;
			    	if(script[i]==']') {
			    		strcpy(txlb,substr(script,mark,i));
			    		strcpy(script,substr(script,i+1,strlen(script)));
			    		break;
			    	}
			    }
			    strcpy(list[lslen].type,alab);
			    strcpy(list[lslen].script,script);
			    strcpy(list[lslen].mark,txlb);
			    list=(elemt*)realloc(list,(++lslen)+1);
				break;
			}
		}
		if(!strcmp(alab,"@End")) break;
    } while(True);
    return list;
}
Bool release(website* web,const char*srvip,const unsigned port) {
	raweb rweb;
	if(anode_wget(&rweb,srvip,port)==False) return False;
	return True;
}
